package store

import (
	"guard/internal/app/admin/models"
	"guard/internal/db"
	"guard/internal/tool"
)

func (s *adminStoreImpl) SelClientPage(current, size int) *tool.Paginator {
	return db.SelPage(&models.ClientInfo{}, current, size, s.db)
}

func (s *adminStoreImpl) SelClientQuery(id string, clientName string) (mc *models.ClientInfo, err error) {
	err = s.db.Where("client_id = ?", id).Or("client_name = ?", clientName).First(&mc).Error
	return
}

func (s *adminStoreImpl) SaveClient(info models.ClientInfo) error {
	return s.db.Save(&info).Error
}

func (s *adminStoreImpl) UpdateClient(info models.ClientInfo) error {
	return s.db.Model(&models.ClientInfo{}).Where("client_id =?", info.ClientId).Updates(info).Error
}

func (s *adminStoreImpl) DelClient(id string) error {
	err := s.db.Exec("delete from oauth2_registered_client where client_id = ?", id).Error
	return err
}

/**
用户client管理
*/

func (s *adminStoreImpl) SelUserApp(username string) (mu []models.UserApp, err error) {
	err = s.db.Raw("select * from user_app where user_name = ?", username).Scan(&mu).Error
	return
}

func (s *adminStoreImpl) SaveUserApp(app models.UserApp) error {
	return s.db.Exec("insert into user_app(user_name, client_id, client_secret, client_name) VALUES (?,?,?,?)", app.UserName, app.ClientId, app.ClientSecret, app.ClientName).Error
}

func (s *adminStoreImpl) DelUserApp(username, cid string) error {
	return s.db.Exec("delete from user_app where user_name = ? and client_id = ?", username, cid).Error
}

func (s *adminStoreImpl) SelUserAppCount(username string) (count int, err error) {
	err = s.db.Raw("select count(client_id) from user_app where user_name = ?", username).Scan(&count).Error
	return
}
